import Taro from "@tarojs/taro"
import store from '@/store/user';
import config from "./config"

type resType = {
  data: any,
  code: number
}
const uploadFile = function (url, tempFilePath, form?: {[key: string]: any}) {
  const userInfo = store.info
  const token = userInfo?.token || ''
	return new Promise<resType>((resolve, reject) => {
		Taro.uploadFile({
			url: `${config.BASE_URL}${url}`,
			filePath: tempFilePath,
			name: 'file',
			formData: {
				path: 'src/',
				...form
			},
			header: {
				token,
				'content-type': 'multipart/form-data'
			},
			success: res => {
				try {
					const data = JSON.parse(res.data) as resType
					if (data.code === 0) {
						resolve(data)
					} else {
						reject(data)
					}
				} catch (e) {
					console.error(e)
					reject(e)
				}
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

export { uploadFile }
